<template>
  <div>
    <!-- 1. Page Title -->
    <h1>{{ pageTitle }}</h1>

    <!-- 2. Main Product Form (Basic Info + Other Settings) -->
    <el-form
      :model="visaProductForm"
      :rules="visaProductRules"
      ref="productForm"
      class="product-form"
      label-position="left"
      label-width="80px"
      v-loading="isLoadingData"
    >
      <!-- Section Title (Optional visual separator) -->
      <h2 class="form-section-title">基本信息</h2>

      <el-row :gutter="20">
        <!-- Country -->
        <el-col :span="6">
          <el-form-item label="国家" prop="countryId">
            <el-select v-model="visaProductForm.countryId" placeholder="请选择国家" style="width: 100%;">
              <el-option
                v-for="item in countryOptions"
                :key="item.id"
                :label="item.countryName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- Continent -->
        <el-col :span="6">
          <el-form-item label="大洲" prop="continent">
            <el-select v-model="visaProductForm.continent" placeholder="请选择大洲" style="width: 100%;">
              <el-option
                v-for="item in continentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- Region -->
        <el-col :span="6">
          <el-form-item label="领区" prop="regionId">
            <el-select v-model="visaProductForm.regionId" placeholder="请选择领区" style="width: 100%;">
              <el-option
                v-for="item in regionOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- Visa Type -->
        <el-col :span="6">
          <el-form-item label="有效期限" prop="visaTypeId">
            <el-input 
              v-model="visaProductForm.visaTypeId" 
              placeholder="例如：三个月"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- Product Name -->
        <el-col :span="12">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="visaProductForm.name" placeholder="请输入签证名称" />
          </el-form-item>
        </el-col>

        <!-- Transact Time -->
        <el-col :span="12">
          <el-form-item label="办理时长" prop="transactTime">
            <el-input 
              v-model="visaProductForm.transactTime" 
              placeholder="请输入工作日数量" 
              type="number"
            >
              <template slot="append">个工作日</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- Price -->
        <el-col :span="12">
          <el-form-item label="产品价格" prop="price">
            <el-input 
              v-model="visaProductForm.price" 
              type="number" 
              step="0.01"
              min="0"
              placeholder="请输入价格（支持两位小数）">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>

        <!-- Expire Date -->
        <el-col :span="12">
          <el-form-item label="有效期限" prop="expireDate">
            <el-date-picker
              v-model="visaProductForm.expireDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyyMMdd"
              :picker-options="pickerOptions"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- Max Stay -->
        <el-col :span="12">
          <el-form-item label="最长停留" prop="maxStay">
            <el-input v-model="visaProductForm.maxStay" placeholder="例如：30天" />
          </el-form-item>
        </el-col>

        <!-- Entry Number -->
        <el-col :span="12">
          <el-form-item label="入境次数" prop="entryNumber">
            <el-select v-model="visaProductForm.entryNumber" placeholder="请选择入境次数" style="width: 100%;">
              <!-- 使用 number 类型的值 -->
              <el-option label="不限" :value="-1"></el-option>
              <el-option label="1次" :value="1"></el-option>
              <el-option label="多次" :value="99"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- Section Title (Optional visual separator) -->
      <h2 class="form-section-title">其他设置</h2>

      <el-row :gutter="20">
         <el-col :span="12">
            <el-form-item label="热门产品" prop="isHot">
              <!-- 使用 '1' 和 '0' 作为字符串值 -->
              <el-switch
                v-model="visaProductForm.isHot"
                active-text="是"
                inactive-text="否"
                active-value="1"
                inactive-value="0">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品状态" prop="isShow">
              <el-switch
                v-model="visaProductForm.isShow"
                active-text="上线"
                inactive-text="下线"
                active-value="1"
                inactive-value="0">
              </el-switch>
            </el-form-item>
         </el-col>
      </el-row>

      <!-- 用户须知 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="用户须知" prop="userNotice">
            <el-input
              type="textarea"
              v-model="visaProductForm.userNotice"
              placeholder="请输入用户须知，最多15000个字"
              :maxlength="15000"
              rows="10"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form> <!-- End of Main Product Form -->

    <!-- 3. Template Configuration Form -->
    <!-- Template Configuration Form -->
    <h1 class="section-header">模板配置</h1>
    <el-form
      :model="templateConfig"
      :rules="templateRules"
      ref="templateForm"
      class="template-form"
      label-position="left"
      label-width="100px"
      v-loading="isLoadingData"
    >
      <!-- 添加全部模板的控制开关 -->
      <el-row>
        <el-col :span="24">
          <el-checkbox 
            v-model="useGlobalTemplate"
            @change="handleGlobalTemplateChange"
          >启用全局模板</el-checkbox>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- 全部模板选项 -->
        <el-col :span="12">
          <el-form-item label="全部" :prop="'templates.0'">
            <el-select
              v-model="templateConfig.templates[0]"
              placeholder="请选择模板"
              style="width: 100%;"
              clearable
              :disabled="!useGlobalTemplate"
            >
              <el-option
                v-for="template in allTemplateOptions"
                :key="template.id"
                :label="template.name"
                :value="template.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <!-- 其他申请人群模板 -->
        <el-col :span="12" v-for="group in applicantGroups" :key="group.id">
          <el-form-item :label="group.name" :prop="'templates.' + group.id">
            <el-select
              v-model="templateConfig.templates[group.id]"
              placeholder="请选择模板"
              style="width: 100%;"
              clearable
              :disabled="useGlobalTemplate"
            >
              <el-option
                v-for="template in groupedTemplateOptions[group.name]"
                :key="template.id"
                :label="template.name"
                :value="template.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form> <!-- End of Template Configuration Form -->

    <!-- 4. Action Buttons -->
    <div class="action-buttons">
      <el-button
        round
        type="primary"
        @click="submitForm"
        :loading="isSubmitting"
      >
        确认提交
      </el-button>
      <el-button round @click="cancelForm" :disabled="isSubmitting">
        取消
      </el-button>
    </div>

  </div>
</template>

<script>
import axios from "@/utils/request";

// --- Constants defined outside the component ---
const CONTINENT_OPTIONS = [
  {value: '亚洲', label: '亚洲'},
  {value: '欧洲', label: '欧洲'},
  {value: '北美洲', label: '北美洲'},
  {value: '南美洲', label: '南美洲'},
  {value: '非洲', label: '非洲'},
  {value: '大洋洲', label: '大洋洲'},
  {value: '南极洲', label: '南极洲'},
];

const APPLICANT_GROUPS = [
  { id: 1, name: "在职人员" },
  { id: 2, name: "自由职业者" },
  { id: 3, name: "退休人员" },
  { id: 4, name: "在校学生" },
  { id: 5, name: "学龄前儿童" }
];
// --- End Constants ---

export default {
  name: 'VisaProductForm', // Add a component name
  data() {
    // Helper function for required rule
    const requiredRule = (message, trigger = 'change') => ({
      required: true, message, trigger
    });

    return {
      isEdit: false,
      useGlobalTemplate: false, // 控制是否使用全局模板
      isLoadingData: false, // Loading state for initial data
      isSubmitting: false,  // Loading state for submission
      visaProductForm: { // Initialize all fields to prevent reactivity issues
        id: null,          // Important for edit mode
        countryId: '',
        continent: '',
        regionId: '',
        visaTypeId: '',
        name: '',
        transactTime: '',
        price: null,       // Use null or '' for number inputs initially
        expireDate: [], // 改为数组存储开始和结束日期
        maxStay: '',
        entryNumber: null, 
        userNotice: '',
        isHot: '0',       
        isShow: '0',
      },
      countryToContinentMap: {
    '中国': '亚洲',
    '日本': '亚洲',
    '韩国': '亚洲',
    '美国': '北美洲',
    '加拿大': '北美洲',
    '墨西哥': '北美洲',
    '巴西': '南美洲',
    '阿根廷': '南美洲',
    '智利': '南美洲',
    '哥伦比亚': '南美洲',
    '德国': '欧洲',
    '法国': '欧洲',
    '英国': '欧洲',
    '意大利': '欧洲',
    '西班牙': '欧洲',
    '葡萄牙': '欧洲',
    '希腊': '欧洲',
    '瑞士': '欧洲',
    '荷兰': '欧洲',
    '瑞典': '欧洲',
    '俄罗斯': '欧洲',
    '土耳其': '亚洲',
    '印度': '亚洲',
    '新加坡': '亚洲',
    '泰国': '亚洲',
    '阿联酋': '亚洲',
    '沙特阿拉伯': '亚洲',
    '以色列': '亚洲',
    '越南': '亚洲',
    '马来西亚': '亚洲',
    '印度尼西亚': '亚洲',
    '南非': '非洲',
    '埃及': '非洲',
    '肯尼亚': '非洲',
    '摩洛哥': '非洲',
    '尼日利亚': '非洲',
    '澳大利亚': '大洋洲',
    '新西兰': '大洋洲',
    '哈萨克斯坦': '亚洲',
    '阿塞拜疆': '亚洲',
    '格鲁吉亚': '亚洲',
    '巴拿马': '北美洲',
    '阿曼': '亚洲',
    '卡塔尔': '亚洲',
    '挪威': '欧洲',
    '丹麦': '欧洲',
    '爱尔兰': '欧洲',
    '捷克': '欧洲',
    '哥斯达黎加': '北美洲',
    '冰岛': '欧洲'
      },
      visaProductRules: {
        countryId: [requiredRule('请选择国家')],
        continent: [requiredRule('请选择大洲')],
        regionId: [requiredRule('请选择领区')],
        visaTypeId: [requiredRule('例如三个月')],
        name: [requiredRule('请输入签证名称', 'blur')], // Use blur for text inputs
        transactTime: [requiredRule('请输入办理时长', 'blur')],
        price: [
          requiredRule('请输入价格', 'blur'),
          { 
            validator: (rule, value, callback) => {
              if (value === '' || value === null) {
                callback(new Error('请输入价格'));
              } else if (isNaN(value)) {
                callback(new Error('请输入有效的数字'));
              } else if (value < 0) {
                callback(new Error('价格不能为负数'));
              } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
                callback(new Error('最多支持两位小数'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        expireDate: [requiredRule('请输入有效期限', 'blur')],
        maxStay: [requiredRule('请输入最长停留时间', 'blur')],
        entryNumber: [requiredRule('请选择入境次数')],
         // No rules needed for isHot/isShow unless required
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
        }
      },
      // Options fetched from API
      countryOptions: [],
      regionOptions: [],
      visaTypeOptions: [],
      templateOptions: [], // All available templates

      // Template Configuration
      templateConfig: {
        templates: {} // Structure: { groupId: templateId }
      },
      templateRules: {
      },
      continentOptions: CONTINENT_OPTIONS,
      applicantGroups: APPLICANT_GROUPS,
    };
  },
  computed: {
    pageTitle() {
      return this.isEdit ? '编辑签证产品' : '添加签证产品';
    },
    productId() {
      // Get product ID from route params if editing
      return this.$route.params.id || null;
    },
    allTemplateOptions() {
      return this.templateOptions.filter(template => template.fieldGroup === '全部');
    },
    // Pre-group template options by applicant group name
    groupedTemplateOptions() {
      const grouped = {};
      APPLICANT_GROUPS.forEach(group => {
        // Filter templates matching the current group's name
        grouped[group.name] = this.templateOptions.filter(template => template.fieldGroup === group.name);
      });
      return grouped;
    }
  },
  created() {
    this.isEdit = this.$route.params.mode === 'edit';
    this.initData();
    this.initializeTemplateConfig();
  },

  watch: {
    // 监听国家选择变化
    'visaProductForm.countryId': {
      handler(newVal) {
        if (newVal) {
          // 根据选择的国家ID找到对应的国家名称
          const selectedCountry = this.countryOptions.find(country => country.id === newVal);
          if (selectedCountry) {
            // 根据国家名称找到对应的大洲
            const continent = this.countryToContinentMap[selectedCountry.countryName];
            if (continent) {
              this.visaProductForm.continent = continent;
            }
          }
        }
      },
      immediate: true
    }
  },

  methods: {
        // 处理全局模板开关变化
        handleGlobalTemplateChange(val) {
      if (val) {
        // 启用全局模板时，清空其他所有模板的选择
        Object.keys(this.templateConfig.templates).forEach(key => {
          if (key !== '0') {
            this.$set(this.templateConfig.templates, key, '');
          }
        });
      } else {
        // 禁用全局模板时，清空全局模板的选择
        this.$set(this.templateConfig.templates, 0, '');
      }
    },
    initializeTemplateConfig() {
      this.$set(this.templateConfig.templates, 0, '');
      // 初始化其他申请人群的选项
      APPLICANT_GROUPS.forEach(group => {
        if (!this.templateConfig.templates.hasOwnProperty(group.id)) {
          this.$set(this.templateConfig.templates, group.id, '');
        }
      });
    },

    async initData() {
      this.isLoadingData = true;
      try {
        // Fetch options concurrently
        await Promise.all([
          this.fetchOptions(),
          this.fetchTemplateOptions()
        ]);

        if (this.isEdit && this.productId) {
          await this.fetchVisaProductDetail(this.productId);
        }
      } catch (error) {
        console.error("Initialization failed:", error);
      } finally {
        this.isLoadingData = false;
      }
    },

    async fetchOptions() {
      try {
        const [countryRes, visaTypeRes, regionRes] = await Promise.all([
          axios.get("/admin/template/countries"),
          axios.get("/admin/template/visa-types"),
          axios.get("/admin/template/regions")
        ]);

        this.countryOptions = countryRes.code === 1 ? countryRes.data : [];
        this.visaTypeOptions = visaTypeRes.code === 1 ? visaTypeRes.data : [];
        
        // 处理领区数据，将"全部领区"置顶
        if (regionRes.code === 1) {
          const regions = regionRes.data || [];
          this.regionOptions = regions.sort((a, b) => {
            if (a.name === '全部领区') return -1;
            if (b.name === '全部领区') return 1;
            return 0;
          });
        } else {
          this.regionOptions = [];
        }

        if (countryRes.code !== 1 || visaTypeRes.code !== 1 || regionRes.code !== 1) {
          this.countryOptions = countryRes.data;
          this.updateCountryToContinentMap();
          console.error("Failed to fetch some options:", { countryRes, visaTypeRes, regionRes });
          this.$message.error('获取基础选项数据失败，请稍后重试');
        }
      } catch (error) {
        this.$message.error('网络错误，无法获取选项数据');
        console.error('fetchOptions error:', error);
      }
    },

    
    // 添加更新映射关系的方法
    updateCountryToContinentMap() {
      // 如果后端返回的国家数据中包含大洲信息，就用它来更新映射关系
      this.countryOptions.forEach(country => {
        if (country.countryName && country.continent) {
          this.$set(this.countryToContinentMap, country.countryName, country.continent);
        }
      });
    },

    async fetchTemplateOptions() {
      try {
        const res = await axios.get('/admin/templates/list');
        if (res.code === 1) {
          this.templateOptions = res.data || [];
        } else {
          throw new Error(res.msg || '获取模板列表失败');
        }
      } catch (error) {
        this.$message.error(error.message || '获取模板列表时发生错误');
        console.error('fetchTemplateOptions error:', error);
      }
    },

    async fetchVisaProductDetail(id) {
      try {
        // 并行请求产品详情和模板数据
        const [productRes, templateRes] = await Promise.all([
          axios.get(`/admin/visaProduct/${id}`),
          axios.get(`/admin/vueVisaProduct/template/${id}`)
        ]);

        // 处理产品详情数据
        if (productRes.code === 1 && productRes.data) {
          console.log('从后端获取的数据:', productRes.data);  // 修改这里

          // 处理日期范围数据
          if (productRes.data.startDate && productRes.data.endDate) {  // 修改这里
            this.visaProductForm.expireDate = [productRes.data.startDate, productRes.data.endDate];
          } else if (productRes.data.startDate) {  // 修改这里
            this.visaProductForm.expireDate = [productRes.data.startDate, productRes.data.startDate];
          }

          // 处理其他字段
          Object.keys(this.visaProductForm).forEach(key => {
            if (productRes.data.hasOwnProperty(key)) {
              if (key === 'price' || key === 'entryNumber') {
                this.visaProductForm[key] = productRes.data[key] !== null ? Number(productRes.data[key]) : null;
              } else if (key === 'isHot' || key === 'isShow') {
                this.visaProductForm[key] = String(productRes.data[key]);
              } else if (key === 'transactTime') {
                // 回显时自动去掉“个工作日”后缀，只保留数字
                const match = String(productRes.data[key]).match(/^(\d+)/);
                this.visaProductForm[key] = match ? Number(match[1]) : '';
              } else if (key !== 'expireDate') {
                this.visaProductForm[key] = productRes.data[key];
              }
            }
          });

          console.log('设置后的表单数据:', this.visaProductForm);
          this.visaProductForm.id = productRes.data.id;  // 修改这里

          // 处理模板数据
          if (templateRes.code === 1 && templateRes.data) {
            console.log('获取到的原始模板数据:', JSON.stringify(templateRes.data, null, 2));
            const loadedTemplates = {};
            
            templateRes.data.forEach(template => {
              console.log('处理单个模板:', template);
              // 查找对应的组ID
              const group = APPLICANT_GROUPS.find(g => g.name === template.applicantGroupId);
              if (group && template.templateId) {
                console.log('找到对应的组:', group.name, '组ID:', group.id);
                loadedTemplates[group.id] = Number(template.templateId);
              }
            });
            
            // 确保所有分组都有一个值
            APPLICANT_GROUPS.forEach(group => {
              if (!loadedTemplates.hasOwnProperty(group.id)) {
                loadedTemplates[group.id] = '';
              }
            });
            
            console.log('最终处理后的模板数据:', JSON.stringify(loadedTemplates, null, 2));
            this.templateConfig.templates = loadedTemplates;
          } else {
            console.log('没有找到模板数据，初始化空配置');
            this.initializeTemplateConfig();
          }

        } else {
          throw new Error(res.msg || '获取签证产品信息失败');  // 修改这里
        }
      } catch (error) {
        this.$message.error(`加载产品信息失败: ${error.message}`);
        console.error('fetchVisaProductDetail error:', error);
        // Optionally navigate back or show an error state
        this.$router.push('/main/visaProduct');
      }
    },

    async submitForm() {
      this.isSubmitting = true;
      try {
        // Validate both forms concurrently
        const productFormValid = await this.$refs.productForm.validate();
        const templateFormValid = await this.$refs.templateForm.validate();

        if (!productFormValid || !templateFormValid) {
          this.$message.error('请检查表单，修正错误后提交');
          this.isSubmitting = false;
          return;
        }

        
      const templateConfigs = this.useGlobalTemplate
        ? [{ applicantGroupId: 0, templateId: Number(this.templateConfig.templates[0]) }]
        : Object.entries(this.templateConfig.templates)
            .filter(([groupId, templateId]) => templateId && groupId !== '0')
            .map(([groupId, templateId]) => ({
              applicantGroupId: Number(groupId),
              templateId: Number(templateId)
            }));

        // 准备签证产品数据
        const payload = {
          ...this.visaProductForm,
          countryId: Number(this.visaProductForm.countryId),
          regionId: Number(this.visaProductForm.regionId),
          price: Number(this.visaProductForm.price),
          entryNumber: Number(this.visaProductForm.entryNumber),
          startDate: this.visaProductForm.expireDate[0],
          endDate: this.visaProductForm.expireDate[1],
          transactTime: this.visaProductForm.transactTime+'个工作日',
          templateConfigs: Object.entries(this.templateConfig.templates)
            .filter(([groupId, templateId]) => templateId)
            .map(([groupId, templateId]) => ({
              applicantGroupId: Number(groupId),
              templateId: Number(templateId)
            })),
        };

        if (!this.isEdit) {
          delete payload.id;
        }

        // 保存签证产品信息
        const apiUrl = '/admin/visaProduct';
        const apiMethod = this.isEdit ? 'put' : 'post';

        const res = await axios({
          url: apiUrl,
          method: apiMethod,
          data: payload
        });

        if (res.code === 1) {
          // 获取产品ID（编辑模式使用现有ID，新建模式使用返回的ID）
          const productId = this.isEdit ? this.visaProductForm.id : res.data;
          
          // 准备模板关联数据
          const templatePayload = {
            productId: productId,
            templateIds: Object.values(this.templateConfig.templates)
              .filter(templateId => templateId) // 过滤掉空值
              .map(templateId => Number(templateId)) // 转换为数字
          };

          // 调用新接口保存模板关联
          const templateRes = await axios.post('/admin/vueVisaProduct/template', templatePayload);
          
          if (templateRes.code === 1) {
            this.$message.success(this.isEdit ? '签证产品修改成功' : '签证产品添加成功');
            this.$router.push('/main/visaProduct');
          } else {
            throw new Error(templateRes.msg || '模板关联保存失败');
          }
        } else {
          throw new Error(res.msg || (this.isEdit ? '修改失败' : '添加失败'));
        }
      } catch (error) {
        if (error && error.message) {
          this.$message.error(`提交失败: ${error.message}`);
        } else {
          this.$message.error('提交时发生未知错误');
        }
        console.error('submitForm error:', error);
      } finally {
        this.isSubmitting = false;
      }
    },

    cancelForm() {
      this.$confirm('确认取消？未保存的更改将丢失。', '提示', {
        confirmButtonText: '确定取消',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }).then(() => {
        this.$router.push('/main/visaProduct');
      }).catch(() => {
        this.$message.info('操作已取消');
      });
    }
  }
}
</script>

<style scoped>
/* General Styling */
.product-form, .template-form {
  border: 1px solid #dcdfe6;
  padding: 25px;
  border-radius: 8px; 
  margin-bottom: 30px;
  background-color: #fff; 
}

h1 {
  margin-bottom: 20px; 
  font-size: 1.8em;
  color: #303133;
}

/* Section Titles */
.form-section-title {
  font-size: 1.2em;
  color: #606266;
  padding-bottom: 10px;
  margin-top: 10px; 
  margin-bottom: 20px; 
  border-bottom: 1px solid #e4e7ed; 
}

/* Header for Template Config Section */
.section-header {
    margin-top: 30px; 
    margin-bottom: 15px;
    font-size: 1.5em;
    color: #303133;
}


/* Make selects and inputs full width within their columns */
.el-select {
  width: 100%;
}

/* Action Buttons */
.action-buttons {
  text-align: center;
  margin-top: 30px; 
  padding-bottom: 20px;
}

.action-buttons .el-button {
  margin-left: 10px;
  margin-right: 10px;
  min-width: 120px; 
}

.el-form-item .el-switch {
    height: auto; 
}

</style>
